package com.sun.controller.front;

import com.alibaba.fastjson.JSON;
import com.sun.pojo.User;
import com.sun.service.UserService;
import com.sun.utils.SystemConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/register")
    @ResponseBody
    public String register(User user){
        HashMap<String, Object> map = new HashMap<String, Object>();
        if(userService.addUser(user)>0){
            map.put(SystemConstant.SUCCESS,true);
            map.put(SystemConstant.MESSAGE,"注册成功!");
        }else{
            map.put(SystemConstant.SUCCESS,false);
            map.put(SystemConstant.MESSAGE,"注册失败,请重新注册!");
        }
        return JSON.toJSONString(map);
    }

    @RequestMapping("/checkUserExist")
    @ResponseBody
    public String checkUserExist(String loginName){
        HashMap<String, Object> map = new HashMap<String, Object>();
        if(userService.checkUserExist(loginName)==null){
            map.put(SystemConstant.EXIST,false);
        }else{
            map.put(SystemConstant.EXIST,true);
            map.put(SystemConstant.MESSAGE,"用户名已存在,请重新输入!");
        }
        return JSON.toJSONString(map);
    }

    @RequestMapping("/login")
    @ResponseBody
    public String login(String loginName, String password, HttpSession session){
        HashMap<String, Object> map = new HashMap<String, Object>();
        User loginUser = userService.login(loginName, password);
        if(loginUser!=null){
            map.put(SystemConstant.SUCCESS,true);
            session.setAttribute(SystemConstant.FRONT_LOGINUSER,loginUser);
        }else{
            map.put(SystemConstant.SUCCESS,false);
            map.put(SystemConstant.MESSAGE,"用户名或密码错误,请验证后登录!");
        }
        return JSON.toJSONString(map);
    }
}
